package com.programmercarl.dp;

/**
 * https://leetcode.cn/problems/partition-equal-subset-sum/description/
 * 416. 分割等和子集 AC
 *
 * @author yulongtian
 * @create 2025-02-16 22:22
 */
public class Test08_02 {
    public static void main(String[] args) {
        Test08_02 test0801 = new Test08_02();
        System.out.println(test0801.canPartition(new int[]{1, 2, 3, 5}));
    }

    /**
     * 尝试使用动态规划
     *
     * @param nums
     * @return
     */
    public boolean canPartition(int[] nums) {
        int n = nums.length;
        if (n == 1) {
            return false;
        }
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += nums[i];
        }
        if (sum % 2 != 0) {
            return false;
        }
        int bag = sum / 2;
        int[][] dp = new int[n][bag + 1];
        // 初始化
        for (int j = nums[0]; j <= bag; j++) {
            dp[0][j] = nums[0];
        }
        for (int i = 1; i < n; i++) {
            for (int j = 0; j <= bag; j++) {
                // 不放
                if (j < nums[i]) {
                    dp[i][j] = dp[i - 1][j];
                } else {
                    // 放
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - nums[i]] + nums[i]);
                }
            }
        }
        return dp[n - 1][bag] == bag;
    }

}
